#!/usr/bin/perl
#
# Add an administrator to the Linux Counter databases
#
# Arguments:
# $1 userid
# $2 wanted name
# $3 placeid he wants to be maintainer for
#
use strict;
use warnings;

use Counter;
use Fcntl;
use Apache::Htpasswd;
use Getopt::Long;

use vars qw($userno $username $placeid);
use vars qw($users $user $person $places $place $pwf $pw);
use vars qw($test $DEBUG);

$test = 1;

GetOptions("test!" => \$test,
	   "debug" => \$DEBUG,
	   );

$userno = shift;
$username = shift;
$placeid = shift;

if (!$userno || !$username) {
    die "Usage: $0 userno username [placeid]\n";
}

$users = Counter::open(O_RDWR);

$user = $users->get($userno);
if (!$user) {
    die "User $userno does not exist\n";
}
if ($user->{login} && $username && $user->{login} ne $username) {
    die "User $userno already has username $$user{login}\n";
}

my $otheruser = $users->getbykey("login", $username);
if ($otheruser) {
    die "login $username is in use by ", $otheruser->key(), "\n";
}

$pwf = new Apache::Htpasswd("$ENV{COUNTER_ROOT}/access/users");

# following test should only hit when inconsistency occurs
$pw = $pwf->fetchPass($username);
print "TEST: $pw :TEST";
if ($pw) {
    die "login $username already has password entry in htpasswd\n";
}

if ($placeid) {
    $places = Counter::openfile("places");
    $place = $places->getbykey("name", $placeid);
    if (!$place) {
	die "No such place as $placeid - can't manage that\n";
    }
}

$person = $user->person();
if (!$person) {
    die "User $userno has no person entry\n";
}

# Print out some information
print "Adding user $userno with login $username to manage $placeid\n";
print "The user's name is $$person{name}\n"
    if $$person{name};
print "The user's state is $$user{state}\n";
print "The user's email is $$person{email} (private $$user{email})\n";
if ($placeid) {
    print "The place is $placeid $$place{longname}\n";
    print "The present maintainers are $$place{maintainer}\n"
	if $$place{maintainer};
}
if ($test) {
    warn "Skipping writes - test mode\n";
}
# Go on to add
my $password = $user->{key};
$password =~ s/^\d+-//;
$user->{login} = $username;
$user->store() if !$test;
$DEBUG && warn "Setting password for $username to $password\n";
$pwf->htpasswd($username, $password) if !$test;
if ($placeid) {
    if ($$place{maintainer}) {
	$$place{maintainer} .= " $userno";
    } else {
	$$place{maintainer} = $userno;
    }
    $place->store() if !$test;
}







